import threading
import time
import os, json
from datetime import datetime
import generalization
import feedparser
import random
import hashlib
import requests

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.sms.v20210111 import sms_client, models



rssList = {
    "生活": 'https://news.yahoo.co.jp/rss/categories/life.xml',
    "国际": 'https://news.yahoo.co.jp/rss/categories/domestic.xml',
    "国内": 'https://news.yahoo.co.jp/rss/categories/world.xml',
    "经济": 'https://news.yahoo.co.jp/rss/categories/business.xml',
    "娱乐": 'https://news.yahoo.co.jp/rss/categories/entertainment.xml',
    "运动": 'https://news.yahoo.co.jp/rss/categories/sports.xml',
    "IT": 'https://news.yahoo.co.jp/rss/categories/it.xml',
    "科学": 'https://news.yahoo.co.jp/rss/categories/science.xml',
}

# 百度翻译 api 的 appKey 和 appSecret
appKey = '20231012001844862'
appSecret = 'y8xDHW_3h3sWzE6zypIq'
class BaiDuFanyi:
    def __init__(self, appKey, appSecret):
        self.url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
        self.appid = appKey
        self.secretKey = appSecret
        self.fromLang = 'auto'
        self.toLang = 'zh'
        self.salt = random.randint(32768,65536)
        self.header = {'Content-Type': 'application/x-www-form-urlencoded'}
    def BdTrans(self,text):
        sign = self.appid + text + str(self.salt) + self.secretKey
        md = hashlib.md5()
        md.update(sign.encode(encoding='utf-8'))
        sign =md.hexdigest()
        data = {
            "appid": self.appid,
            "q": text,
            "from": self.fromLang,
            "to": self.toLang,
            "salt": self.salt,
            "sign": sign
        }
        response = requests.post(self.url, params= data, headers= self.header)  # 发送post请求
        text = response.json()  # 返回的为json格式用json接收数据
        results = ""
        for i in range(0, len(text['trans_result'])):   # 遍历所有的 dst
            results += text['trans_result'][i]['dst'] + '\n\n'
        return results

rssList_title = {}
current_directory = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(current_directory, "records.json")

def update_rssList_title():
    global rssList_title
    rssList_title.clear()

    # 读取 JSON 文件
    with open(filename, 'r', encoding='utf-8') as file:
        data = json.load(file)

    for category, url in rssList.items():
        category_exists = False
        for item in data:
            if item.get('category') == category:
                category_exists = True
                break

        if not category_exists: continue

        print(category)
        feed = feedparser.parse(url)

        if category not in rssList_title:
            rssList_title[category] = []

        for index, entry in enumerate(feed.entries[:10]):
            description = entry.description

            BaiduTranslate_test = BaiDuFanyi(appKey, appSecret)
            translation = BaiduTranslate_test.BdTrans(description)

            quest = "把下面这段中文缩写到12个汉字以内，不要标点符号，不要保留英文，只有一句中文: "
            quest += translation
            ans = generalization.main(quest)
            ans = ans[:12]

            rssList_title[category].append(ans)

def send_msg(phone, category):
    try:
        cred = credential.Credential("AKIDZ7lNdliZQ9nGbt8HJApU8c7WmxH5mGWb", "5K6jMdjgT3sjU5ogcPyKWjssEb7X1PfC")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "sms.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = sms_client.SmsClient(cred, "ap-nanjing", clientProfile)

        req = models.SendSmsRequest()
        params = {
            "PhoneNumberSet": [ phone ],
            "SmsSdkAppId": "1400877989",
            "SignName": "摸鱼科技公众号",
            "TemplateId": "2026861",
            "TemplateParamSet": [ category, rssList_title[category][0], rssList_title[category][1], rssList_title[category][2], rssList_title[category][3], rssList_title[category][4], rssList_title[category][5], rssList_title[category][6], rssList_title[category][7], rssList_title[category][8], rssList_title[category][9] ],
        }
        req.from_json_string(json.dumps(params))

        resp = client.SendSms(req)
        print(resp.to_json_string())

    except TencentCloudSDKException as err:
        print(err)

def send_msg_every_hour():
    print("send_msg_every_hour start...")
    if not os.path.exists(filename):
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump({}, f)

    while True:
        now = datetime.now()

        if now.minute == 0 and now.second == 0: # send every hours
            update_rssList_title()
            print("update success: %s" % datetime.now())

            with open(filename, 'r', encoding='utf-8') as f:
                records = json.load(f)
                print(records)

            for record in records:
                send_msg(record['phone'], record['category'])


            time.sleep(53 * 60)  # sleep 50 minutes

send_msg_every_hour()

